/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.risk.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.hazardsource.domain.CheckListEntry;
import com.koron.hazardsource.domain.CheckListItem;
import com.koron.hazardsource.mapper.CheckListEntryMapper;
import com.koron.hazardsource.mapper.CheckListItemMapper;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.bean.SourceQueryBean;
import com.koron.risk.domain.LocalCheckListEntry;
import com.koron.risk.domain.LocalCheckListItem;
import com.koron.risk.domain.LocalHazardSource;
import com.koron.risk.domain.LocalRisk;
import com.koron.risk.mapper.*;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LocalHazardSourceApprovalServiceImpl implements AfterApprovalService, InitializingBean {
    private final static Logger logger= LoggerFactory.getLogger(LocalHazardSourceApprovalServiceImpl.class);

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(LocalHazardSource.class.getName(), this);
    }
    
    @Value("${checklistEntryTypeId}")
    private String checklistEntryTypeId;
    
    
    @Autowired
    private FlowManagement flowManagement;

    @SuppressWarnings("deprecation")
    @Override
    public void editApproval(Audit audit) {
        List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
        try (SessionFactory factory = new SessionFactory();) {
            LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
            LocalRiskMapper lrMapper = factory.getMapper(LocalRiskMapper.class);
            List<LocalHazardSource> list = lhsMapper.queryByIdList("local_hazard_source_history", idList);
            for (LocalHazardSource lhs : list) {
                lhs.setState(1);
                lhs.setFstatusflag(2);
                List<LocalRisk> lrList = lrMapper.queryBySourceId("local_risk_history", lhs.getId());
                lhs.setRisks(lrList);
            }
            save(list);
            updateFstatusflag(idList, 2);
        }

    }
    
    
    
    @Override
	public void processDiscard(Audit audit) {
		// TODO Auto-generated method stub
		
	}



	@SuppressWarnings({"deprecation"})
    @Override
    public void discardApproval(Audit audit) {
        List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
        try(SessionFactory factory = new SessionFactory()) {
        	LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
            List<LocalHazardSource> list = lhsMapper.queryByIdList("local_hazard_source_history", idList);
            List<String> codeList = list.stream().map(LocalHazardSource::getCode).collect(Collectors.toList());
            updateState(codeList, 0);
		} catch (Exception e) {
            logger.error(e.getMessage(),e);
		}
    }

    @SuppressWarnings("deprecation")
    public void updateState(List<String> codeList, int state) {
        try (SessionFactory factory = new SessionFactory();) {
            LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
            lhsMapper.updateState(codeList, state);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @SuppressWarnings("deprecation")
    public void updateDisposalState(List<String> idList, int disposalState) {
        try (SessionFactory factory = new SessionFactory();) {
            LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
            lhsMapper.updateDisposalState(idList, disposalState);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }


    @SuppressWarnings("deprecation")
    public void updateFstatusflag(List<String> idList, int fstatusflag) {
        try (SessionFactory factory = new SessionFactory();) {
            LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
            lhsMapper.updateFstatusflag(idList, fstatusflag);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @SuppressWarnings("deprecation")
    public void save(List<LocalHazardSource> lhsList) {
        SessionFactory factory = new SessionFactory();
        try {
            LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
            LocalRiskMapper lrMapper = factory.getMapper(LocalRiskMapper.class);

            List<LocalCheckListEntry> lceList = new ArrayList<LocalCheckListEntry>();
            List<LocalCheckListItem> lciList = new ArrayList<LocalCheckListItem>();
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);

            CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
            CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);

            Date date = new Date();
            for (LocalHazardSource lhs : lhsList) {
            	String oldId = lhs.getId();
                Integer rowNo = lhs.getRowNo();
                List<LocalRisk> lrList = lhs.getRisks();
                String code = lhs.getCode();
                if (StringUtils.isEmpty(lhs.getTemplateCode())) {
                    lhs.setExclusive(1); //专有
                    lhs.setDisposalState(0);//未处理
                }else{
                	lhs.setExclusive(0); //标准导入
                }
                if (StringUtils.isEmpty(code)) {
                    //新增
                    String id = DefaultIdGenerator.getInstance().generateLongId();
                    code = generateCode(factory, lhs);
                    lhs.setCode(code);
                    lhs.setAddTime(date);
                    //是否已存在
                    LocalHazardSource oldLhs = lhsMapper.queryByCode("local_hazard_source", code);
                    if (oldLhs == null) {
                    	lhs.setId(id);
                        lhsMapper.insert("local_hazard_source", lhs);
                        lhsMapper.updateCode(oldId, lhs.getCode());
                    } else {
                        //先删除风险项
                        id = oldLhs.getId();
                        lrMapper.deleteBySourceId("local_risk", id);
                        lhs.setId(id);
                        lhs.setUpdateTime(date);
                        lhsMapper.update("local_hazard_source", lhs);
                    }
                    for (LocalRisk lr : lrList) {
                        lr.setId(DefaultIdGenerator.getInstance().generateLongId());
                        lr.setAddTime(date);
                        lr.setLocalHazardId(lhs.getId());
                    }
                    lrMapper.batchInsert("local_risk", lrList);
                } else {
                    LocalHazardSource oldLhs = lhsMapper.queryByCode("local_hazard_source", code);
                    if (oldLhs == null) {
                        //新增
                        String id = DefaultIdGenerator.getInstance().generateLongId();
                        code = generateCode(factory, lhs);//新code
                        lhs.setCode(code);
                        lhs.setAddTime(date);
                        oldLhs = lhsMapper.queryByCode("local_hazard_source", code);
                        if (oldLhs == null) {
                        	lhs.setId(id);
                            lhsMapper.insert("local_hazard_source", lhs);
                            lhsMapper.updateCode(oldId, lhs.getCode());
                        } else {
                            id = oldLhs.getId();
                            lrMapper.deleteBySourceId("local_risk", id);
                            lhs.setId(id);
                            lhs.setUpdateTime(date);
                            lhsMapper.update("local_hazard_source", lhs);
                        }
                        for (LocalRisk lr : lrList) {
                            lr.setId(DefaultIdGenerator.getInstance().generateLongId());
                            lr.setAddTime(date);
                            lr.setLocalHazardId(lhs.getId());
                        }
                        lrMapper.batchInsert("local_risk", lrList);
                    } else {
                        //修改
                        //先删除风险项
                        String id = oldLhs.getId();
                        lrMapper.deleteBySourceId("local_risk", id);
                        lhs.setId(id);
                        lhs.setUpdateTime(date);
                        for (LocalRisk lr : lrList) {
                            lr.setId(DefaultIdGenerator.getInstance().generateLongId());
                            lr.setAddTime(date);
                            lr.setLocalHazardId(lhs.getId());
                        }
                        lhsMapper.update("local_hazard_source", lhs);
                        lrMapper.batchInsert("local_risk", lrList);
                    }
                }
                //生成检查表
                LocalCheckListEntry lce = lceMapper.queryByCode("local_checklist_entry", code);
                if (lce == null) {
                    lce = new LocalCheckListEntry();
                    lce.setId(DefaultIdGenerator.getInstance().generateLongId());
                    lce.setCorpCode(lhs.getCorpCode());
                    lce.setName(lhs.getName()+"检查表");
                    lce.setCode(lhs.getCode());
                    lce.setAddTime(lhs.getAddTime());
                    lce.setAddUser(lhs.getAddUser());
                    lce.setAddUserName(lhs.getAddUserName());
                    lce.setBusinessTypeId(lhs.getBusinessTypeId());
                    lce.setLocalHazardSourceId(lhs.getId());
                    lce.setChecklistEntryTypeId(checklistEntryTypeId == null?"1164813482886750208":checklistEntryTypeId);
                    lce.setState(1);
                    lce.setFstatusflag(1);
                    
                    String templateCode = lhs.getTemplateCode();
                    if (StringUtils.isEmpty(templateCode)) {
                        lce.setHasItems(0);
                    } else {
                        CheckListEntry cle = cleMapper.queryByCode("checklist_entry", templateCode);
                        lce.setHasItems(0);
                        if (cle != null) {
                            lce.setTemplateCode(templateCode);
                            lce.setHasItems(cle.getHasItems());
                            List<CheckListItem> cliList = cliMapper.queryItemsInByEntryId("checklist_item", cle.getId(), null, null);
                            for (CheckListItem cli : cliList) {
                                LocalCheckListItem lci = new LocalCheckListItem();
                                lci.setId(DefaultIdGenerator.getInstance().generateLongId());
                                lci.setAddUser(lce.getAddUser());
                                lci.setAddTime(lce.getAddTime());
                                lci.setLocalChecklistEntryId(lce.getId());
                                lci.setItemIndex(cli.getItemIndex());
                                lci.setKeyword(cli.getKeyword());
                                lci.setName(cli.getName());
                                lci.setLocalChecklistEntryId(lce.getId());
                                lciList.add(lci);
                            }
                        }
                    }
                    lceList.add(lce);
                }
            }
            if (lceList.size() > 0) {
                //插入检查表
                lceMapper.batchInsert("local_checklist_entry", lceList);
                if (lciList.size() > 0) {
                    lciMapper.batchInsert("local_checklist_item", lciList);
                }
            }
            factory.close();
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
        }
    }

    public String generateCode(SessionFactory factory, LocalHazardSource lhs) {
        String convert = "";
        CorpManagementMapper corpMapper = factory.getMapper(CorpManagementMapper.class);
        CorpBean corpBean = corpMapper.get(lhs.getCorpCode());
        if (corpBean == null) {
            convert = "#####";
        }
        convert = corpBean.getShortCode();
        if (StringUtils.isEmpty(convert)) {
            convert = "#####";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("W");
        Integer count = 0;
        if (StringUtils.isEmpty(lhs.getTemplateCode())) {
        	Boolean all = lhs.getFitAllBusiness();
        	LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
            if (all) {
            	SourceQueryBean queryBean = new SourceQueryBean();
            	queryBean.setTableName("local_hazard_source");
            	queryBean.setFitAllBusiness(all);
            	queryBean.setCorpCode("('"+lhs.getCorpCode()+"')");
            	count = lhsMapper.count(queryBean);
            	sb.append("C");
            } else {
            	String businessValue = "";
                String hazardValue = "";
                DictDataMapper ddMapper = factory.getMapper(DictDataMapper.class);
                DictData businessType = ddMapper.queryOne(lhs.getBusinessTypeId());
                if (businessType != null) {
                    businessValue = businessType.getDictValue();
                }
                DictData hazardType = ddMapper.queryOne(lhs.getHazardTypeId());
                if (hazardType != null) {
                    hazardValue = hazardType.getDictValue();
                }
                sb.append(businessValue).append(hazardValue);
                SourceQueryBean queryBean = new SourceQueryBean();
                queryBean.setTableName("local_hazard_source");
                queryBean.setBusinessTypeId(lhs.getBusinessTypeId());
                queryBean.setHazardTypeId(lhs.getHazardTypeId());
                queryBean.setCorpCode("('"+lhs.getCorpCode()+"')");
                count = lhsMapper.count(queryBean);
            }
            count++;
            NumberFormat nf = NumberFormat.getInstance();
            nf.setGroupingUsed(false);
            nf.setMaximumIntegerDigits(3); // 设置最大整数位数
            nf.setMinimumIntegerDigits(3); // 设置最小整数位数
            sb.append(nf.format(count));
        } else {
            sb.append(lhs.getTemplateCode());
        }
        sb.append("-").append(convert);
        return sb.toString();
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
